package myJs.common

import myJs.Implicits._
import myJs.cps.Style
import myJs.cps.project.QrcodeCp
import myJs.myPkg._
import myJs.myPkg.jquery.$
import myJs.myPkg.reactBootstrap.Modal
import myJs.tool.Pojo.ImageData
import myJs.tool.Tool
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.web.html._
import typings.csstype.csstypeStrings

import scala.concurrent.Future

/**
 * Created by yz on 21/1/2022
 */
@react object QrcodesModalCp {

  case class Props(show: Boolean = false, showChange: Boolean => Unit, sampleIds: List[String])

  val component = FunctionalComponent[Props] { props =>

    object FTool {

      def handleClose = () => {
        props.showChange(false)
      }

      def downloadQrcode = () => {
        val zip = new JSZip()
        val es = $(".qrcodeBox .img").es
        val dataFs = es.map { y =>
          val id = $(y).find("p").text().trim.replaceAll("^PN:", "")
          DomToImage.toPng(y).toFuture.map { url =>
            ImageData(id = id, url = url)
          }
        }
        Future.sequence(dataFs).map { datas =>
          datas.foreach { data =>
            val id = data.id
            val fileName = s"${id}.png"
            val imageData = data.url.replaceAll("^data:image/png;base64,", "")
            zip.file(fileName, imageData, JSZipOptions(base64 = true))
          }
          zip.generateAsync(GenerateOptions(`type` = "blob")).toFuture.foreach { content =>
            FileSaver.saveAs(content, s"qrcode_${es.size}.zip")
          }
        }
        ()
      }


      def createTempNode = {
        $("#prepare_print_block").html($("#show_qrcode_body").html())
        $("#prepare_print_block").find(".qrcodeBox .print-download-btns-parent").remove()
      }

      def printAll = () => {
        createTempNode
        Tool.printClick
        ()
      }

    }

    Modal(onHide = FTool.handleClose, show = props.show, size = "qrcodesModal",
    )(
      Modal.Header(bsPrefix = "modal-header bg-primary", closeButton = true)(
        Modal.Title(
          span(style := Style(fontWeight = "bold"), id := "lblAddTitle", s" 二维码信息(批量操作)")
        )
      ),
      Modal.Body(
        div(style := Style(display = csstypeStrings.flex),
          div(id := "result", style := Style(),
            div(id := "download", style := Style(),
              button(className := "btn btn-primary", data - "value" := "ko_dodge.png",
                onClick := FTool.downloadQrcode,
                style := Style(marginLeft = "15px"),
                i(className := "fa fa-download"),
                s" 全部下载",
              ),
              button(className := "btn btn-primary", data - "value" := "ko_dodge.png",
                onClick := FTool.printAll,
                style := Style(marginLeft = "15px"),
                i(className := "fa fa-print"),
                s" 全部打印",
              )
            ),
            div(id := "qrcodeResult", style := Style(display = csstypeStrings.flex, flexWrap = csstypeStrings.wrap,
              justifyContent = csstypeStrings.left),
              div(id := "show_qrcode_body", style := Style(display = csstypeStrings.flex, flexWrap = csstypeStrings.wrap,
                maxHeight = 750, overflowY = csstypeStrings.auto),
                props.sampleIds.zipWithIndex.map { case (idStr, curI) =>
                  QrcodeCp(key = s"${curI}", sampleId = idStr)
                }
              ),
              div(style := Style(width = "1px", height = "1px", overflow = "hidden",
                position = csstypeStrings.relative,
                backgroundColor = "#fff"),
                div(style := Style(position = csstypeStrings.absolute, right = "300px"),
                  ul(id := "prepare_print_block")
                )
              )
            )
          )
        ),
      ),
      Modal.Footer(bsPrefix = "modal-footer bg-info")(
        button(`type` := "button", className := "btn green", data - "dismiss" := "modal", "取消",
          onClick := FTool.handleClose),
      )

    )

  }


}
